package com.fyy.netty.chapter01.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author fyy
 * @Description 多线程实现服务器
 * 实现思路：
 *  1. 一个线程专门处理客户端的连接ACCEPT事件
 *  2. 多线程处理客户端的读写READ\WRITE事件
 * @Date 2021/4/23 9:29
 */
@Slf4j
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        //指定主线程名称
        Thread.currentThread().setName("BOSS"); //负责处理客户端连接事件
        ServerSocketChannel ssc = ServerSocketChannel.open(); //创建服务器连接
        ssc.configureBlocking(false); //设置为非阻塞模式
        Selector boss = Selector.open(); //声明选择器
        SelectionKey bossKey = ssc.register(boss, 0, null); //注册选择器
        bossKey.interestOps(SelectionKey.OP_ACCEPT); //关注连接事件
        ssc.bind(new InetSocketAddress(8080)); //绑定端口
        //创建多个Worker,并初始化
        Worker[] workers = new Worker[5];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-"+i);
        }
        AtomicInteger index = new AtomicInteger();
        while (true){
            boss.select();
            Iterator<SelectionKey> keys = boss.selectedKeys().iterator();
            while (keys.hasNext()) {
                SelectionKey key = keys.next(); //获取事件的key
                keys.remove(); //删除事件,防止重复处理
                if(key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    log.info("创建连接{}",sc.getRemoteAddress());
                    sc.configureBlocking(false); //设置为非阻塞模式
                    //关联
                    workers[index.getAndIncrement() % workers.length].register(sc); //worker初始化
                }
            }
        }
    }

    static class Worker implements Runnable{
        private String name; //线程名称
        private Selector selector; //Selector
        private Thread thread; //工作线程
        private volatile boolean start = false; //是否已创建线程及Selector

        public Worker(String name) {
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                selector = Selector.open();
                thread = new Thread(this,name);
                thread.start(); //启动线程
                start = true;
            }
            selector.wakeup(); //唤醒
            sc.register(selector,SelectionKey.OP_READ,null);
        }

        //执行读写事件
        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
                    while (keys.hasNext()) {
                        SelectionKey key = keys.next();
                        keys.remove();
                        if(key.isReadable()){
                            SocketChannel sc = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            sc.read(buffer);
                            buffer.flip();
                            log.info("内容" + StandardCharsets.UTF_8.decode(buffer));
                            buffer.clear();
                        }
                    }
                } catch (IOException e) {
                    log.error("处理读写事件异常：{}",e.getMessage());
                }
            }
        }
    }

}
